package net.plankton.events;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import net.plankton.agents.Agent;
import net.plankton.context.Context;
import net.plankton.context.occurrence.Occurrence;
import net.plankton.selectors.Action;
import net.plankton.selectors.Selector;

public class GenericOccurrence extends Occurrence{
	
	private Agent agent;
	
	public void setAgent(Agent a) {
		agent = a;
	}
	
	public GenericOccurrence(double percent, String description,Context context) {
		this.desc = description;
		this.percent=percent;
		this.context = context;
	}
	
	public GenericOccurrence(Selector selector, String description,Context context) {
		this.desc = description;
		this.selector=selector;
		this.context = context;
	}
	
	private Selector selector;
	private double percent;
	private String desc;
	protected Context context;
	
	protected List<Agent> agents = new ArrayList<Agent>();
	
	protected Action action;
	
	public void addAction(Action action) {
		this.action = action;
	}
	
	public void addAgent(Agent a) {
		agents.add(a);
	}
	
	@Override
	public String describe() {
		return desc;
	}
	
	public boolean isRelevant() {
		if (selector!=null)
			return selector.isRelevant(context);
		else return Math.random()<percent;
	}

	@Override
	public void happen() {
		if (describe().toLowerCase().indexOf("agent")==-1)
			context.getOutput().output(agent,describe());
		for (Iterator<Agent> it = agents.iterator();it.hasNext();) {
			Agent a = it.next();
			if (a.isRelevant()) {
				a.happen();
				if (action!=null)
					action.execute(context);
				break;
			}
//			else {
//				context.getOutput().output("checking for :"+a.describe()+" -> negative");
//			}
		}
		Collections.shuffle(agents);
	}
	
}
